/*
 * @Description: 新建、编辑 移交归档单
 * @Author: Rfan
 * @Date: 2022-08-03 20:29:15
 * @LastEditTime: 2022-08-04 11:10:48
 */

import { Key, useEffect, useState } from 'react';
import { Form, Input, Select, Space } from 'antd';
import { fetchATListByFondId } from '@/api/archivesType';
import { fetchFondsListByUnitId } from '@/api/fonds';
import { selectItemByKey } from '@/utils/list';
import { appState } from '@/store/mobx';
import { useBackupContext } from '../../../contexts/BackupContext';
import type { FC } from 'react';
import type { FormInstance } from 'antd';

const { Option } = Select;

interface TransferFormProps {
  data?: any;
  form: FormInstance;
  visible: boolean;
  closeDialog: any;
}

const PlanForm: FC<TransferFormProps> = (props) => {
  console.log('common form', props.data);
  const { data, form, visible, closeDialog } = props;
  const { addTransferFunc, editTransferFunc } = useBackupContext();

  // 是否编辑
  const [editFlag, setEditFlag] = useState(false);
  // 部门列表
  // const [departmentList, setDepartmentList] = useState([]);
  // 全宗列表
  const [fondList, setFondList] = useState([]);
  // 档案类型列表
  const [atList, setAtList] = useState([]);
  // 档案类型加载状态
  const [atLoading, setAtLoading] = useState(false);
  // 选中的档案类型
  const [selectAT, setSelectAT] = useState(atList[0] || {});

  useEffect(() => {
    if (visible) {
      if (data?.id) {
        setEditFlag(true);
        form.setFieldsValue(data);
      }
      fetchFondsListByUnitId(appState.unitId).then((res) => {
        setFondList(res.data);
      });
    }
  }, [visible]);

  /**
   * @description 切换全宗方法
   * @param {any} value 切换的全宗ID
   * @return {*}
   */
  const handleFondChange = (value: Key): void => {
    setAtLoading(true);
    fetchATListByFondId(value)
      .then((res) => {
        setAtList(res.data);
        res.data.length > 0 && setSelectAT(res.data[0]);
      })
      .finally(() => {
        setAtLoading(false);
      });
  };

  /**
   * @description 切换档案类型方法
   * @param {Key} value 切换的档案类型ID
   */
  const onATChange = (value: Key) => {
    setSelectAT(selectItemByKey(value, atList));
  };

  // 新增排序方法
  const onFinish = (values: any) => {
    values.archiveTypeName = selectAT.atName;
    values.fondsName = fondList.find((fond) => fond.id === values.fondsId)?.fondName || '';

    if (editFlag) {
      // 编辑时附上id
      values.id = data.id;
      // 如果没有动全宗或档案类型的话，由于没有fondsId无法赋值
      // 这几个默认赋之前的值
      if (!values.fondsName) {
        values.fondsName = data.fondsName;
      }
      if (!values.archiveTypeName) {
        values.archiveTypeId = data.archiveTypeId;
        values.archiveTypeName = data.archiveTypeName;
      }
      editTransferFunc(values).then(() => {
        closeDialog();
      });
    } else {
      addTransferFunc(values).then(() => {
        closeDialog();
      });
    }
  };

  return (
    <Form
      form={form}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      preserve={false}
      onFinish={onFinish}
    >
      <Form.Item name="title" label="标题" rules={[{ required: true }]}>
        <Input />
      </Form.Item>
      <Form.Item label="档案类型" rules={[{ required: true }]}>
        <Space>
          <Form.Item name="fondsId" noStyle>
            <Select placeholder="请选择全宗" style={{ width: 120 }} onChange={handleFondChange}>
              {fondList.map((fond) => (
                <Option key={fond.id} value={fond.id}>
                  {fond.fondName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="archiveTypeId" noStyle>
            <Select
              value={selectAT?.id}
              loading={atLoading}
              placeholder="请选择档案类型"
              style={{ width: 120 }}
              onChange={onATChange}
            >
              {atList.map((item: any) => (
                <Option key={item.id} value={item.id}>
                  {item.atName}
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Space>
      </Form.Item>
      <Form.Item label="接收方">
        <Select placeholder="请选择部门" disabled></Select>
      </Form.Item>
      <Form.Item name="reamrk" label="移交说明">
        <Input.TextArea />
      </Form.Item>
    </Form>
  );
};

export default PlanForm;
